package org.ala.tiktools.rpc.plugin.load_balance.selector;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import org.ala.tiktools.rpc.plugin.node.INode;
import org.ala.tiktools.rpc.plugin.node.NodeKey;

/**
 * 随机选择器
 *
 * @author ala
 * @date 2025-04-07 13:31
 */
public class RandomSelector implements ISelector {
    /**
     * 随机返回
     */
    @Override
    public INode select(List<INode> nodes) {
        int b = nodes.size();
        if (b == 0) { return null;}
        if (b == 1) { 
        	return nodes.get(0); 
        }

        //  全程无锁，选择的过程中nodes可能会发生变化
        int c = Integer.MAX_VALUE;
        INode node = null;
        do {
            b = nodes.size();
            if (b == 0) {return null;}

//            c = ThreadLocalRandom.current().nextInt(b);
            double d = ThreadLocalRandom.current().nextDouble();
            c = (int)(d * b);
            try {
                node = nodes.get(c);
            } catch (Exception e) {
                node = null;
            }
        } while (node == null);
        return node;
    }

    @Override
    public void rtt(NodeKey key, long rtt) {
        //  不考虑延迟权重
    }
}
